package com.cst.zju.anime.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;

import com.bestsonic.crawler.model.Bean;
import com.bestsonic.crawler.model.Regex;
import com.bestsonic.crawler.model.Split;
import com.bestsonic.crawler.utils.RegexUtils;
import com.bestsonic.crawler.utils.URLUtils;
import com.cst.zju.anime.dao.AnimeAndTagsMapper;
import com.cst.zju.anime.dao.AnimeMapper;
import com.cst.zju.anime.dao.ClassifyMapper;
import com.cst.zju.anime.dao.DetailMapper;
import com.cst.zju.anime.dao.TagsMapper;
import com.cst.zju.anime.model.Anime;
import com.cst.zju.anime.model.AnimeAndTagsKey;
import com.cst.zju.anime.model.AnimeExample;
import com.cst.zju.anime.model.Classify;
import com.cst.zju.anime.model.ClassifyExample;
import com.cst.zju.anime.model.DetailWithBLOBs;
import com.cst.zju.anime.model.Tags;
import com.cst.zju.anime.model.TagsExample;

public class SpringQtz {

	private static int counter = 0;

	@Resource
	private AnimeMapper animeMapper;

	@Resource
	private DetailMapper detailMapper;

	@Resource
	private AnimeAndTagsMapper animeAndTagsMapper;

	@Resource
	private TagsMapper tagsMapper;

	@Resource
	private ClassifyMapper classifyMapper;
	
	@Transactional
	protected void execute() {
		try {
			int i = 0;
			Map<String, Regex> map = null;
			Map<String, Regex> mapTag = null;
			Map<String, Regex> mapClassify = new LinkedHashMap<String, Regex>();

			String content = URLUtils.getContent("http://www.hltm.cc/");
			List<String> list = RegexUtils.Regex(content, null,
					new Regex("<a target=\"_self\" href=\"(.*?)\" rel=\"nofollow\">", 1, "http://www.hltm.cc", ""));

			mapClassify.put("name", new Regex("(.*?)</a>", 1));
			List<Classify> classifyList = RegexUtils.Regex(content, new Bean<Classify>(Classify.class,
					new Split[] { new Split(1, "__\\.html\" rel=\"nofollow\">") }, mapClassify));
			String currentUrl = null;
			String nextUrl = null;
			for (String everyUrl : list) {
				currentUrl = everyUrl;
				while (!(currentUrl.equals(nextUrl))) {
					if (nextUrl != null)
						currentUrl = nextUrl;
					content = URLUtils.getContent(currentUrl);
					Split[] split = { new Split(1, " <ul class=\"plist02 clearfix\">"),
							new Split("</em>\\s*?</a>\\s*?</li>") };
					map = new LinkedHashMap<String, Regex>();
					map.put("url", new Regex("<a href=\"(.*?)\">", 1));
					map.put("name", new Regex("<p>(.*?)</p>", 1));
					map.put("status", new Regex("<span>(.*?)</span>", 1));
					//map.put("shortpic", new Regex("<img src=\"(.*?)\">", 1));
					map.put("downcount", new Regex("<em>(下载次数?(.*))", 1));
					List<Anime> animeList = RegexUtils.Regex(content, new Bean<Anime>(Anime.class, split, map));
					animeList.remove(animeList.size() - 1);
					System.out.println(animeList);
					ClassifyExample classifyExample = new ClassifyExample();
					classifyExample.createCriteria().andNameEqualTo(classifyList.get(i).getName());
					List<Classify> classifies = classifyMapper.selectByExample(classifyExample);
					Classify classify = null;
					if (classifies.size() > 0) {
						classify = classifies.get(0);
					} else {
						classifyMapper.insertSelective(classifyList.get(i));
						classify = classifyList.get(i);
					}
					for (Anime anime : animeList) {

						anime.setClassifyId(classify.getId());
						AnimeExample animeExample = new AnimeExample();
						animeExample.createCriteria().andNameEqualTo(anime.getName());
						
						List<Anime> selectList = animeMapper.selectByExample(animeExample);
						if(selectList.size() > 0){
							animeMapper.updateByPrimaryKeySelective(anime);
						}
						else{
							animeMapper.insertSelective(anime);
						}
						
						int animeId = anime.getId();

						String detailUrl = anime.getUrl();
						String detailContent = URLUtils.getContent(detailUrl);
						map = new LinkedHashMap<String, Regex>();

						map.put("name", new Regex("<div class=\"bpic l\">\\s*<img alt=\"(.*?)\" src=\"(.*?)\"></div>", 1));
						map.put("status", new Regex("<span>状态</span>\\s*?<p> <em>(.*?)</em></p>", 1));
						map.put("location", new Regex("<li>\\s*?<span>动漫地区</span>\\s*?<p>(.*?)</p>\\s*</li>", 1));
						map.put("language", new Regex("<li>\\s*?<span>配音语言</span>\\s*?<p>(.*?)</p>\\s*?</li>", 1));
						map.put("date", new Regex("<li>\\s*?<span>上映年份</span>\\s*?<p>(.*?)</p>\\s*?</li>", 1));
						map.put("shortpic",
								new Regex("<div class=\"bpic l\">\\s*?<img alt=\"(.*?)\" src=\"(.*?)\"></div>", 2));
						map.put("intropic", new Regex("<img alt=\"[(\\)([\\s\\S]*?)]\"\\s*?src=\"(.*?)\"", 1));
						map.put("intro", new Regex("<div class=\"jianjie l mb20\">([\\s\\S]*?)<div class=\"box01 l\">", 1));
						map.put("tags", new Regex("<li>\\s*?<span>动漫类型</span>\\s*?<p>\\s*?(.*)\\s*?</p>\\s*?</li>", 1));
						map.put("updatedate",
								new Regex("<li>\\s*?<span>最后更新</span>\\s*?<p>\\s*?(.*)\\s*?</p>\\s*?</li>", 1));
						map.put("ftp", new Regex("<h2>FTP下载</h2>\\s*?</div>([\\s\\S]*?)</div>", 1));
						map.put("baidu", new Regex("<h2>百度网盘下载</h2>\\s*?</div>([\\s\\S]*?)</div>", 1));
						map.put("thunder", new Regex("<h2>迅雷快传下载</h2>\\s*?</div>([\\s\\S]*?)</div>", 1));

						DetailWithBLOBs detail = RegexUtils
								.Regex(detailContent, new Bean<DetailWithBLOBs>(DetailWithBLOBs.class, null, map)).get(0);
						detail.setAnimeId(animeId);
						/**
						 * 获得traffic、rate、strdate、episode、lastDate
						 */
						String trafficUrl = RegexUtils.RegexFirst(detailContent, null,
								new Regex(
										"<script language=\"JavaScript\" src=\"(http://www.hltm.cc/api.php\\?op=video_count&id=(.*?))\"></script>",
										1));
						String id = RegexUtils.RegexFirst(detailContent, null,
								new Regex(
										"<script language=\"JavaScript\" src=\"(http://www.hltm.cc/api.php\\?op=video_count&id=(.*?))\"></script>",
										2));
						String trafficContent = URLUtils.getContent(trafficUrl);
						String updateInfoUrl = "http://www.hltm.cc/api.php?op=gengxin&id=" + id;
						String updateInfoContent = URLUtils.getContent(updateInfoUrl);
						String[] splitUpdateInfo = updateInfoContent.split(",");
						if (splitUpdateInfo.length > 1) {
							String strdate = RegexUtils.RegexFirst(splitUpdateInfo[5], null,
									new Regex("\"strdate\":\"(.*?)\"", 1));
							String episode = RegexUtils.RegexFirst(splitUpdateInfo[3], null,
									new Regex("\"state\":\"(.*?)\"", 1));
							Date nextDate = new SimpleDateFormat("yyyy-MM-dd hh:mm").parse(
									RegexUtils.RegexFirst(splitUpdateInfo[4], null, new Regex("\"date\":\"(.*?)\"", 1)));
							detail.setStrdate(strdate);
							detail.setEpisode(episode);
							detail.setNextdate(nextDate);
						}
						String rateUrl = "http://www.hltm.cc/api.php?op=score&id=" + id;
						// {"s":"y","info":{"l":218,"s":9,"s2":"3","s4":"1","s6":"1","s8":"51","s10":"162","user":0}}
						String rateContent = URLUtils.getContent(rateUrl);
						String[] splitRate = rateContent.split(",");
						String numOfPeople = splitRate[1].replace("\"info\":{\"l\":", "");
						String sumOfRate = splitRate[2].replace("\"s\":", "");
						String numOfPerson = RegexUtils.RegexFirst(splitRate[7], null, new Regex("\"s.+?\":\"(.*?)\"", 1))
								+ "-" + RegexUtils.RegexFirst(splitRate[6], null, new Regex("\"s.+?\":\"(.*?)\"", 1)) + "-"
								+ RegexUtils.RegexFirst(splitRate[5], null, new Regex("\"s.+?\":\"(.*?)\"", 1)) + "-"
								+ RegexUtils.RegexFirst(splitRate[4], null, new Regex("\"s.+?\":\"(.*?)\"", 1)) + "-"
								+ RegexUtils.RegexFirst(splitRate[3], null, new Regex("\"s.+?\":\"(.*?)\"", 1));
						String rate = sumOfRate + "-" + numOfPeople + "-" + numOfPerson;

						String traffic = RegexUtils.RegexFirst(trafficContent, null, new Regex("html\\(\'(.*?)\'\\);", 1));
						detail.setRate(rate);
						detail.setTraffic(Long.valueOf(traffic));

						String[] tags = detail.getTags().split("\\s*?、\\s*?");
						for (String str : tags) {

							TagsExample example = new TagsExample();
							example.createCriteria().andNameEqualTo(str);
							List<Tags> tagList = tagsMapper.selectByExample(example);
							Tags tag = null;
							if (tagList.size() > 0) {
								tag = tagList.get(0);
							} else {
								tag = new Tags();
								tag.setName(str);
								tagsMapper.insertSelective(tag);
							}

							int tagid = tag.getId();

							AnimeAndTagsKey animeAndTagsKey = new AnimeAndTagsKey(animeId, tagid);

							animeAndTagsMapper.insertSelective(animeAndTagsKey);
						}
						detailMapper.insertSelective(detail);
						anime.setLocation(detail.getLocation());
						anime.setUpdatedate(detail.getUpdatedate());
						animeMapper.updateByPrimaryKeySelective(anime);
						// StreamUtils.write2File(detailContent, "D:\\webpage.txt");
					}
					List<String> nextPageList = RegexUtils.Regex(content, null,
							new Regex("<a target=\"_self\" href=\"(\\S*?)\" class=\"a1\">\\s*?下一页\\s*?</a>", 1,
									"http://www.hltm.cc", ""));
					System.out.println(nextPageList.size());
					if (nextPageList.size() == 0) {
						nextUrl = currentUrl;
					} else {
						nextUrl = nextPageList.get(0);
					}
					System.out.println(nextUrl);
					System.out.println(currentUrl);
				}
				nextUrl = null;
				i++;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}
